<template>
  <div class="app-container">
    <!-- 主机分组管理界面 -->
    <div class="host-group-management">
      <div class="main-content">
        <!-- 左侧主机分组树 -->
        <div class="panel group-panel">
          <div class="panel-header">
            <span class="panel-title">主机分组</span>
            <el-button
              type="primary"
              :icon="Plus"
              size="small"
              @click="handleAddGroup(null)"
            >新增根组</el-button>
          </div>
          <div class="tree-container">
            <el-tree
              :data="groupTree"
              :props="defaultProps"
              default-expand-all
              node-key="id"
              :expand-on-click-node="false"
              :current-node-key="currentNodeKey"
              highlight-current
              @node-click="handleNodeClick">
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span class="tree-actions">
                    <el-tooltip content="新增子组" placement="top">
                      <el-icon @click="() => handleAddGroup(data)"><CirclePlus /></el-icon>
                    </el-tooltip>
                    <el-tooltip content="编辑" placement="top">
                      <el-icon @click="() => handleEditGroup(data)"><Edit /></el-icon>
                    </el-tooltip>
                    <el-tooltip content="删除" placement="top">
                      <el-icon @click="() => handleDeleteGroup(node, data)"><Delete /></el-icon>
                    </el-tooltip>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
        
        <!-- 右侧主机列表 -->
        <div class="panel host-list-panel">
          <div class="panel-header">
            <span class="panel-title">主机列表 - {{ currentNode ? currentNode.name : '未选择分组' }}</span>
            <div>
              <el-button
                type="primary"
                :icon="Plus"
                size="small"
                :disabled="!currentNode"
                @click="handleAddHosts"
              >批量新增</el-button>
              <el-button
                type="danger"
                :icon="Delete"
                size="small"
                :disabled="multiple"
                @click="handleRemoveHosts"
              >批量移除</el-button>
            </div>
          </div>
          
          <el-table
            v-loading="loading"
            :data="hostList"
            @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="id" align="center" prop="hostId" />
            <el-table-column label="主机名称" align="center" prop="name" />
            <el-table-column label="主机编码" align="center" prop="code" />
            <el-table-column label="主机地址" align="center" prop="address" />
            <el-table-column label="主机状态" align="center" prop="status">
              <template #default="{ row }">
                <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                  {{ statusFormat(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template #default="scope">
                <el-button
                  size="small"
                  type="text"
                  :icon="Delete"
                  @click="handleRemoveHost(scope.row)"
                >移除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :small="true"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="getHostList"
            @current-change="getHostList"
          />
        </div>
      </div>
    </div>

    <!-- 添加或修改主机组对话框 -->
    <el-dialog :title="groupTitle" v-model="groupOpen" width="500px" append-to-body>
      <el-form ref="groupFormRef" :model="groupForm" :rules="groupRules" label-width="80px">
        <el-form-item label="组名称" prop="name">
          <el-input v-model="groupForm.name" placeholder="请输入组名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="groupForm.sort" :min="0" controls-position="right" style="width: 100%" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelGroup">取 消</el-button>
          <el-button type="primary" @click="submitGroupForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 批量添加主机对话框 -->
    <el-dialog title="批量添加主机" v-model="hostSelectOpen" width="80%" append-to-body>
      <div class="dialog-content">
        <el-form :model="hostQueryParams" size="small" :inline="true">
          <el-form-item label="主机编码">
            <el-input
              v-model="hostQueryParams.code"
              placeholder="请输入主机编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="主机地址">
            <el-input
              v-model="hostQueryParams.address"
              placeholder="请输入主机地址"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleHostQuery">搜索</el-button>
            <el-button :icon="Refresh" @click="resetHostQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-table
          v-loading="hostSelectLoading"
          :data="availableHostList"
          @selection-change="handleHostSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="主机名称" align="center" prop="name" />
          <el-table-column label="主机编码" align="center" prop="code" />
          <el-table-column label="主机地址" align="center" prop="address" />
          <el-table-column label="状态" align="center" prop="status">
              <template #default="{ row }">
                <el-tag :type="row.status === '0' ? 'success' : 'danger'">
                  {{ statusFormat(row.status) }}
                </el-tag>
              </template>
          </el-table-column>
        </el-table>

        <el-pagination
          v-model:current-page="hostQueryParams.pageNum"
          v-model:page-size="hostQueryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :small="true"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="hostSelectTotal"
          @size-change="getAvailableHostList"
          @current-change="getAvailableHostList"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="hostSelectOpen = false">取 消</el-button>
          <el-button type="primary" @click="submitAddHosts">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  Delete, 
  Search, 
  Refresh, 
  CirclePlus, 
  Edit 
} from '@element-plus/icons-vue'
import { listGroup, getGroup, delGroup, addGroup, updateGroup, addHostToGroup, selectHostsByGroupBindStatus, removeHostFromGroup } from "@/api/os/group"

// 遮罩层
const loading = ref(false)
const hostSelectLoading = ref(false)

// 选中数组
const ids = ref([])
const hostSelectIds = ref([])

// 非单个禁用
const single = ref(true)
// 非多个禁用
const multiple = ref(true)

// 总条数
const total = ref(0)
const hostSelectTotal = ref(0)

// 主机分组树数据
const groupTree = ref([])

// 当前选中的节点
const currentNode = ref(null)
const currentNodeKey = ref(null)

const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}

// 主机列表
const hostList = ref([])
// 可用主机列表（用于批量添加）
const availableHostList = ref([])

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  hostGroupId: null,
  query: 0 // true表示查询已绑定的主机
})

// 主机查询参数（用于查询未绑定的主机）
const hostQueryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  code: null,
  address: null,
  hostGroupId: null,
  query: 0 // false表示查询未绑定的主机
})

// 主机组对话框
const groupOpen = ref(false)
const groupTitle = ref("")
const groupFormRef = ref()
const groupForm = reactive({
  id: null,
  parentId: null,
  name: null,
  sort: 0,
  remark: null
})

const groupRules = reactive({
  name: [{ required: true, message: "组名称不能为空", trigger: "blur" }]
})

// 主机选择对话框
const hostSelectOpen = ref(false)

// 状态格式化
const statusFormat = (status) => {
  const statusMap = {
    '0': '正常',
    '1': '停用'
  }
  return statusMap[status] || '未知'
}

/** 查询主机分组树 */
const getGroupTree = () => {
  listGroup().then(response => {
    if (response.code === 200) {
      groupTree.value = response.data
    } else {
      ElMessage.error("获取分组列表失败")
    }
  }).catch(error => {
    ElMessage.error("获取分组列表失败")
  })
}

/** 树节点点击事件 */
const handleNodeClick = (data) => {
  currentNode.value = data
  currentNodeKey.value = data.id
  queryParams.hostGroupId = data.id
  getHostList()
}

/** 查询主机列表 */
const getHostList = () => {
  // 如果没有选择分组，不查询
  if (!currentNode.value) {
    hostList.value = []
    total.value = 0
    return
  }
  
  loading.value = true
  selectHostsByGroupBindStatus(queryParams).then(response => {
    if (response.code === 200) {
      hostList.value = response.rows
      total.value = response.total
    } else {
      ElMessage.error("获取主机列表失败")
    }
    loading.value = false
  }).catch(error => {
    loading.value = false
    ElMessage.error("获取主机列表失败")
  })
}

/** 查询可用主机列表（未绑定的） */
const getAvailableHostList = () => {
  hostSelectLoading.value = true
  // 设置当前分组ID和绑定状态
  hostQueryParams.hostGroupId = currentNode.value ? currentNode.value.id : null
  hostQueryParams.query = 1// 查询未绑定的主机
  hostQueryParams.bindStatus = false // 查询未绑定的主机
  
  selectHostsByGroupBindStatus(hostQueryParams).then(response => {
    if (response.code === 200) {
      availableHostList.value = response.rows
      hostSelectTotal.value = response.total
    } else {
      ElMessage.error("获取可用主机列表失败")
    }
    hostSelectLoading.value = false
  }).catch(error => {
    hostSelectLoading.value = false
    ElMessage.error("获取可用主机列表失败")
  })
}

/** 处理主机选择变化 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.hostGroupRelId)
  single.value = selection.length !== 1
  multiple.value = !selection.length
}

/** 处理可用主机选择变化 */
const handleHostSelectionChange = (selection) => {
  hostSelectIds.value = selection.map(item => item.hostId)
}

/** 计算子组排序值 */
const calculateChildSort = (parentData) => {
  if (!parentData.children || parentData.children.length === 0) {
    return 0
  }
  
  // 获取最后一个子组的sort值并加1
  const lastChild = parentData.children[parentData.children.length - 1]
  return lastChild.sort + 1
}

/** 新增主机组 */
const handleAddGroup = (data) => {
  resetGroup()
  
  if (data) {
    // 新增子组
    groupForm.parentId = data.id
    groupForm.sort = calculateChildSort(data)
    groupTitle.value = "新增子组"
  } else {
    // 新增根组
    groupForm.parentId = 0
    
    // 计算根组的排序值
    if (groupTree.value.length > 0) {
      const lastRootGroup = groupTree.value[groupTree.value.length - 1]
      groupForm.sort = lastRootGroup.sort + 1
    } else {
      groupForm.sort = 0
    }
    
    groupTitle.value = "新增根组"
  }
  
  groupOpen.value = true
}

/** 编辑主机组 */
const handleEditGroup = (data) => {
  resetGroup()
  getGroup(data.id).then(response => {
    if (response.code === 200) {
      Object.assign(groupForm, response.data)
      groupTitle.value = "修改主机组"
      groupOpen.value = true
    } else {
      ElMessage.error("获取分组信息失败")
    }
  }).catch(error => {
    ElMessage.error("获取分组信息失败")
  })
}

/** 删除主机组 */
const handleDeleteGroup = (node, data) => {
  ElMessageBox.confirm(`是否确认删除主机组"${data.name}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return delGroup(data.id)
  }).then(response => {
    if (response.code === 200) {
      getGroupTree()
      ElMessage.success("删除成功")
      // 如果删除的是当前选中的节点，清空右侧列表
      if (currentNode.value && currentNode.value.id === data.id) {
        currentNode.value = null
        currentNodeKey.value = null
        hostList.value = []
      }
    } else {
      ElMessage.error("删除失败")
    }
  }).catch(() => {})
}

/** 提交主机组表单 */
const submitGroupForm = () => {
  if (!groupFormRef.value) return
  
  groupFormRef.value.validate((valid) => {
    if (valid) {
      const request = groupForm.id != null ? updateGroup(groupForm) : addGroup(groupForm)
      
      request.then(response => {
        if (response.code === 200) {
          ElMessage.success(groupForm.id != null ? "修改成功" : "新增成功")
          groupOpen.value = false
          getGroupTree()
        } else {
          ElMessage.error("操作失败")
        }
      }).catch(error => {
        ElMessage.error("操作失败")
      })
    }
  })
}

/** 取消主机组对话框 */
const cancelGroup = () => {
  groupOpen.value = false
  resetGroup()
}

/** 重置主机组表单 */
const resetGroup = () => {
  groupForm.id = null
  groupForm.parentId = null
  groupForm.name = null
  groupForm.sort = 0
  groupForm.remark = null
  
  if (groupFormRef.value) {
    groupFormRef.value.resetFields()
  }
}

/** 打开批量添加主机对话框 */
const handleAddHosts = () => {
  if (!currentNode.value) {
    ElMessage.warning("请先选择分组")
    return
  }
  hostSelectOpen.value = true
  resetHostQuery()
  getAvailableHostList()
}

/** 处理主机查询 */
const handleHostQuery = () => {
  hostQueryParams.pageNum = 1
  getAvailableHostList()
}

/** 重置主机查询 */
const resetHostQuery = () => {
  hostQueryParams.pageNum = 1
  hostQueryParams.pageSize = 10
  hostQueryParams.code = null
  hostQueryParams.address = null
  hostQueryParams.hostGroupId = currentNode.value ? currentNode.value.id : null
}

/** 提交添加主机 */
const submitAddHosts = () => {
  if (hostSelectIds.value.length === 0) {
    ElMessage.warning("请选择要添加的主机")
    return
  }
  
  const params = {
    hostGroupId: currentNode.value.id,
    hostIds: hostSelectIds.value // 直接传递数组
  }
  
  addHostToGroup(params).then(response => {
    if (response.code === 200) {
      ElMessage.success("添加成功")
      hostSelectOpen.value = false
      getHostList() // 刷新右侧主机列表
    } else {
      ElMessage.error("添加失败")
    }
  }).catch(error => {
    ElMessage.error("添加失败")
  })
}

/** 批量移除主机 */
const handleRemoveHosts = () => {
  if (ids.value.length === 0) {
    ElMessage.warning("请选择要移除的主机")
    return
  }
  
  ElMessageBox.confirm('是否确认从分组中移除选中的主机？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return removeHostFromGroup(ids.value)
  }).then(response => {
    if (response.code === 200) {
      ElMessage.success("移除成功")
      getHostList() // 刷新列表
    } else {
      ElMessage.error("移除失败")
    }
  }).catch(() => {})
}

/** 单个移除主机 */
const handleRemoveHost = (row) => {
  ElMessageBox.confirm(`是否确认从分组中移除主机"${row.name}"？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return removeHostFromGroup([row.hostGroupRelId])
  }).then(response => {
    if (response.code === 200) {
      ElMessage.success("移除成功")
      getHostList() // 刷新列表
    } else {
      ElMessage.error("移除失败")
    }
  }).catch(() => {})
}

onMounted(() => {
  getGroupTree()
})
</script>

<style scoped>
.host-group-management {
  margin-top: 20px;
}

.main-content {
  display: flex;
  min-height: 500px;
  gap: 20px;
}

.panel {
  background: #fff;
  border-radius: 4px;
  border: 1px solid #e6ebf5;
  padding: 15px;
  display: flex;
  flex-direction: column;
}

.panel-header {
  padding-bottom: 15px;
  margin-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.panel-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
}

.group-panel {
  flex: 1;
  min-width: 300px;
}

.host-list-panel {
  flex: 2;
  min-width: 800px;
}

.tree-container {
  overflow-y: auto;
  flex: 1;
}

.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.tree-actions .el-icon {
  margin-left: 8px;
  color: #606266;
  cursor: pointer;
  font-size: 16px;
}

.tree-actions .el-icon:hover {
  color: #409EFF;
}

.dialog-content {
  min-height: 400px;
}

:deep(.el-tree-node__content) {
  height: 36px;
}
</style>